<?php

/**
 * 因为不喜欢使用 laravel-auth
 * 所以自己重新封装一下 后端登录验证
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/16 15:39
 */

namespace App\Http\Middleware;

use App\Models\SysRolePermissionsModel;
use App\Models\SysUserModel;
use App\Models\SysUserRoleModel;
use App\Models\UserTokenModel;
use App\Services\Web\UserService;
use Closure;
use Illuminate\Support\Facades\Session;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class MaintainAuth
{
    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle($request, Closure $next)
    {
        writeLoToFile('test', '用户ip:', $_SERVER['REMOTE_ADDR']);
        //存session
        if (empty(adminInfo('id'))){
            //根据token,获取用户信息
            $params = $request->header('token');

//            if(empty($params)){
//                $params = $request->header('Token');
//
//            }

            $where[] = ['token', $params ?? -1];
            $where[] = ['status', 4];
            $tokenLogs = UserTokenModel::getUserOne($where);

            if (empty($tokenLogs['user_id'])){
                //没有权限登录，走code
                return response()->json([
                    'code' => 1001,
                    'message' => '登录状态失效',
                    'data' => []
                ]);
            }

            $sysUserOne = SysUserModel::getOneById($tokenLogs['user_id'], '*');

            $systemInit = UserService::getInstance()->getUserInfo($sysUserOne);

            //写入session服务
            Session::put(['admin'=> $systemInit]);
        }

        $user_id = adminInfo('id');
        //权限判断
        $hasPerms = $this->checkAuth($user_id);

        if (!$hasPerms) {
            if ($request->ajax() || $request->wantsJson()) {
                return sendError(1021, '登录状态失效');
            } else {
                dump("您的权限已修改，需要退出重新登录");die;
            }
        }
        return $next($request);
    }

    /**
     * 权限验证
     * @param $adminId
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function checkAuth($adminId): bool
    {
        if ($adminId == 1) return true;
        //检测权限

        //节点标识
        $node = request()->route()->action;
        $nodeID = $node['as'] ?? '';

        //不走授权的控制器及、方法及节点
        $notAuthNodeIDs = [
            '',
            'init'
        ];

        if (in_array($nodeID, $notAuthNodeIDs)) {
            return true;
        }

        //获取登录用户的授权菜单Id
        $menuList = adminInfo('userAuth');

        if (empty($menuList)) {
            return false;
        }

        if (in_array($nodeID, $menuList)) {
            return true;
        }

        return false;
    }
}

